package com.htg.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

public class UtilDateFormat {
    public static final String FORMAT_1 = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_2 = "yyyy/MM/dd";
    public static final String FORMAT_3 = "yyyy.MM.dd";
    public static final String FORMAT_4 = "yyyy年MM月";
    public static final String FORMAT_5 = "yyyy年MM月dd日";
    public static final String FORMAT_6 = "yyyyMM";
    public static final String FORMAT_7 = "yyyy年MM月dd";
    public static final String FORMAT_8 = "a hh:mm:ss";
    public static final String FORMAT_9 = "yyyy-MM-dd HH:mm";

    public static final String FORMAT_10 = "yyyy-MM-dd HH.mm.ss.SSS";
    public static final String FORMAT_11 = "yyyy年MM月dd日HH时mm分ss秒SSS";

    public static final List<String> formats = Arrays.asList(FORMAT_1, FORMAT_2, FORMAT_3, FORMAT_4, FORMAT_5, FORMAT_6, FORMAT_7, FORMAT_8, FORMAT_9, FORMAT_10,FORMAT_11);

    public static String format(long timestamp, String formt) {

        // 将时间戳转换为 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());

        // 定义带毫秒的日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formt);

        // 格式化日期时间
        String formattedDateTime = dateTime.format(formatter);

        return formattedDateTime;
    }


    public static String parse(String dateStr, String format) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            long timestamp = simpleDateFormat.parse(dateStr).getTime();
            return String.valueOf(timestamp);
        } catch (ParseException e) {
            // 解析失败，尝试下一个日期时间格式
            e.printStackTrace();
            return null;
        }
    }


    public static String parseAny(String dateStr) {

        for (int i = 0; i < formats.size(); i++) {
            String format = formats.get(i);
            String str = parse(dateStr, format);
            if (str != null) {
                return str;
            } else {

            }
        }
        return null;
    }
}
